import { Injectable } from '@nestjs/common';
import { DbService } from '../../db/db.service';
import { CacheService } from '@app/cache';
import UpdateInfoDto from './dto/info.dto';
import { UploadService } from '../upload/upload.service';

@Injectable()
export class UserService {
    private readonly prefix = 'user:';

    constructor(
        private readonly db:DbService,
        private readonly cache:CacheService,
        private readonly upload:UploadService,
    ) {}

    setCache(id:number, user:any) {
        return this.cache.hmset(this.prefix + id, user)
    }

    getFromCache(id:number) {
        return this.cache.hgetall(this.prefix + id)
    }

    async getUserBalance(userId) {
        return this.db.user.findOne({id : userId}, ['amount', 'rewardAmount'])
    }

    async updateInfo(data:UpdateInfoDto, userId:number) {
        const user = await this.db.user.findOne({id : userId}, {nickname : true, avatar : true})

        if(data.avatar != user.avatar || data.nickname != user.nickname) {
            const r = await this.db.user.update({id : userId}, data)
            if(r > 0) {
                if(data.avatar && data.avatar != user.avatar) {
                    this.upload.del(user.avatar)
                }
                return true
            }
        }


        
        return false
    }


    // async balanceRecord(query:Pagination, userId:number) {
    //     let where:FindOptionsWhere<UserWalletLog> = { userId }
    //     const lastId = query.lastKey || 0
    //     const pageSize = query.pageSize || 20

    //     if(lastId > 0) {
    //         where.id = LessThan(lastId)
    //     }

    //     let rows:UserWalletLog[] = await this.userWalletLog.find({
    //         where,
    //         skip : 0, 
    //         take : pageSize, 
    //         order : {id : 'DESC'}
    //     })

    //     return rows
    // }
}
